package com.example.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 全局自定义过滤器，实现GatewayFilter接口,实现ordered就扣，可用于实现过滤器的优先级
 * 加入到容器中生效
 */

@Component

public class GlobalFilter implements GatewayFilter , Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //exchange是一个请求上下文对象，里面包含了请求和响应的信息
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String uri = request.getURI().toString();
        //记录时间
        long startTime = System.currentTimeMillis();
        System.out.println("请求路径是："+uri+"，请求时间是："+startTime);

        //==================
        //放行请求,链式传入下一个拦截器中
        Mono<Void> filter = chain.filter(exchange)
                .doFinally((result)->{
                    //chain方法时异步的，需要用doFinally方法来时放行后执行一些操作
                    long endTime = System.currentTimeMillis();
                    System.out.println("请求路径是："+uri+"，请求时间是："+startTime+"，响应时间是："+(endTime-startTime));
                });


        return filter;


    }


    //优先级，返回值越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
